<?php
// +----------------------------------------------------------------------
// | Iecms [ Make the most exquisite CMS ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009~2019 http://www.iemoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: iemoo <i@iemoo.com>
// +----------------------------------------------------------------------
// | DateTime: 2019/11/19 11:08
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\common\model\Admin as AdminModel;
use app\common\model\AdminGroup as AdminGroupModel;

use app\admin\validate\Login as LoginValidate;
use think\exception\ValidateException;

use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use think\facade\Config;




class Login extends Base
{

	
    public function __construct()
    {
	}

    // 登录页面
    public function index()
    {
        return View::fetch();
    }

    // 校验登录
    public function login(){
        if (Request::isPost()) {

            $data	= Request::only(['username', 'password', 'verify', '__token__']);

            try {
				validate(LoginValidate::class)->check($data);
			} catch (ValidateException $e) {
				// 验证失败 输出错误信息
				$this->error($e->getError());
			}

			$where['username'] = $data['username'];
			$where['password'] = md5(Config::get('app.password_salt') . $data['password']);
			$admin_user = AdminModel::where($where)->findOrEmpty();		

			if (!$admin_user->isEmpty()) {

				if ($admin_user->status != 1) {
					$this->error('当前用户已禁用');
				} else {

					Session::set('admin.id', $admin_user->id);
					Session::set('admin.name', $admin_user->username);
					$group = AdminGroupModel::find($admin_user->admin_group_id);
					Session::set('admin.rules', $group->rules);

					$admin_user->login_time = time();
					$admin_user->login_ip = Request::ip();
					$admin_user->save();
					
					$this->success('登录成功', url('admin/index/index'));
				}
			} else {
				$this->error('用户名或密码错误');
			}

        }
    }

    // 退出登录
    public function logout(){
        Session::delete('admin');
        $this->success('退出成功', url('admin/login/index'));
    }
}
